package com.wct.genetic;

import java.io.*;
import java.util.Collections;
import java.util.List;

/**
 * @author WEI
 * @date 2018/5/30 20:06
 */
public class TspThread extends Thread {

    private String name;
    private TspGenetic genetic;
    private List<TspSolution> tspSolutionList;

    public TspThread(String name, TspGenetic genetic, List<TspSolution> tspSolutionList) {
        this.name = name;
        this.genetic = genetic;
        // 浅拷贝 （不同的子线程操作同一个list对象）
//        this.tspSolutionList = tspSolutionList;
        // 深拷贝 （不同的子线程操作不同的list对象，数据彼此独立，只在初始阶段内容数据一样）
        try {
            this.tspSolutionList = DeepCopy.deepCopy(tspSolutionList);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        super.run();
        int count = 0;
        while (count <= 10000) {
            // 获取两个祖先
            TspSolution father = genetic.getAncestor(tspSolutionList);
            TspSolution mother = genetic.getAncestor(tspSolutionList);
            // 产生后代
            TspSolution child = genetic.doCombined(father, mother);
            // 根据根据适应度（1/weight）选择性替代，权重越小适应度越大
            if (child.getWeight() < father.getWeight() && child.getWeight() < mother.getWeight()) {
                // child适应度比father和mother都大
                if (father.getWeight() > mother.getWeight()) {
                    tspSolutionList.remove(father);
                } else {
                    tspSolutionList.remove(mother);
                }
                tspSolutionList.add(child);
            } else if (child.getWeight() > father.getWeight() && child.getWeight() < mother.getWeight()) {
                // child适应度比father小，比mother大
                tspSolutionList.remove(mother);
                tspSolutionList.add(child);
            } else if (child.getWeight() < father.getWeight() && child.getWeight() > mother.getWeight()) {
                // child适应度比father大，比mother小
                tspSolutionList.remove(father);
                tspSolutionList.add(child);
            }
            count++;
        }


//        System.out.println("进化10000代后的种群：");
//        for (TspSolution s : tspSolutionList) {
//            System.out.println(s.toString());
//        }
        
        // 排序解集
      Collections.sort(tspSolutionList);
      if (tspSolutionList.get(0).getWeight() < 40000) {
          System.out.println(name);
          System.out.println(tspSolutionList.get(0).toString());
      }

    }

}
